/**
 * 网络请求管理器
 * 提供统一的网络请求接口，包含缓存、重试、拦截器等功能
 */

import { logInfo, logWarn, logError } from './errorHandler.js'
import { setCache, getCache, deleteCache } from './cacheManager.js'

/**
 * 请求方法枚举
 */
export const REQUEST_METHODS = {
	GET: 'GET',
	POST: 'POST',
	PUT: 'PUT',
	DELETE: 'DELETE',
	PATCH: 'PATCH',
	HEAD: 'HEAD',
	OPTIONS: 'OPTIONS'
}

/**
 * 请求状态枚举
 */
export const REQUEST_STATUS = {
	PENDING: 'pending',
	SUCCESS: 'success',
	ERROR: 'error',
	CANCELLED: 'cancelled',
	TIMEOUT: 'timeout'
}

/**
 * 缓存策略枚举
 */
export const CACHE_STRATEGIES = {
	NO_CACHE: 'no-cache',
	CACHE_FIRST: 'cache-first',
	NETWORK_FIRST: 'network-first',
	CACHE_ONLY: 'cache-only',
	NETWORK_ONLY: 'network-only',
	STALE_WHILE_REVALIDATE: 'stale-while-revalidate'
}

/**
 * 重试策略枚举
 */
export const RETRY_STRATEGIES = {
	LINEAR: 'linear',
	EXPONENTIAL: 'exponential',
	FIXED: 'fixed',
	CUSTOM: 'custom'
}

/**
 * 网络状态枚举
 */
export const NETWORK_STATUS = {
	ONLINE: 'online',
	OFFLINE: 'offline',
	UNKNOWN: 'unknown'
}

/**
 * 请求配置类
 */
class RequestConfig {
	constructor(options = {}) {
		this.url = options.url || ''
		this.method = options.method || REQUEST_METHODS.GET
		this.data = options.data || null
		this.headers = options.headers || {}
		this.timeout = options.timeout || 10000
		this.retries = options.retries || 3
		this.retryDelay = options.retryDelay || 1000
		this.retryStrategy = options.retryStrategy || RETRY_STRATEGIES.EXPONENTIAL
		this.cacheStrategy = options.cacheStrategy || CACHE_STRATEGIES.NETWORK_FIRST
		this.cacheTTL = options.cacheTTL || 5 * 60 * 1000 // 5分钟
		this.enableCache = options.enableCache !== false
		this.enableRetry = options.enableRetry !== false
		this.enableInterceptors = options.enableInterceptors !== false
		this.validateStatus = options.validateStatus || ((status) => status >= 200 && status < 300)
		this.transformRequest = options.transformRequest || null
		this.transformResponse = options.transformResponse || null
		this.onUploadProgress = options.onUploadProgress || null
		this.onDownloadProgress = options.onDownloadProgress || null
		this.cancelToken = options.cancelToken || null
		this.withCredentials = options.withCredentials || false
		this.responseType = options.responseType || 'json'
		this.maxContentLength = options.maxContentLength || -1
		this.maxBodyLength = options.maxBodyLength || -1
		this.priority = options.priority || 1
		this.tags = options.tags || []
		this.metadata = options.metadata || {}
	}
	
	/**
	 * 生成缓存键
	 * @returns {string} 缓存键
	 */
	generateCacheKey() {
		const keyData = {
			url: this.url,
			method: this.method,
			data: this.data,
			headers: this.headers
		}
		
		return `network_cache_${this.hashCode(JSON.stringify(keyData))}`
	}
	
	/**
	 * 计算字符串哈希码
	 * @param {string} str - 字符串
	 * @returns {string} 哈希码
	 */
	hashCode(str) {
		let hash = 0
		if (str.length === 0) return hash.toString()
		
		for (let i = 0; i < str.length; i++) {
			const char = str.charCodeAt(i)
			hash = ((hash << 5) - hash) + char
			hash = hash & hash // 转换为32位整数
		}
		
		return Math.abs(hash).toString()
	}
}

/**
 * 请求响应类
 */
class RequestResponse {
	constructor(data, status, headers, config, request) {
		this.data = data
		this.status = status
		this.statusText = this.getStatusText(status)
		this.headers = headers || {}
		this.config = config
		this.request = request
		this.timestamp = Date.now()
		this.fromCache = false
		this.retryCount = 0
	}
	
	/**
	 * 获取状态文本
	 * @param {number} status - 状态码
	 * @returns {string} 状态文本
	 */
	getStatusText(status) {
		const statusTexts = {
			200: 'OK',
			201: 'Created',
			204: 'No Content',
			400: 'Bad Request',
			401: 'Unauthorized',
			403: 'Forbidden',
			404: 'Not Found',
			500: 'Internal Server Error',
			502: 'Bad Gateway',
			503: 'Service Unavailable'
		}
		
		return statusTexts[status] || 'Unknown'
	}
}

/**
 * 请求错误类
 */
class RequestError extends Error {
	constructor(message, code, config, request, response) {
		super(message)
		this.name = 'RequestError'
		this.code = code
		this.config = config
		this.request = request
		this.response = response
		this.timestamp = Date.now()
		this.isNetworkError = !response
		this.isTimeout = code === 'TIMEOUT'
		this.isCancelled = code === 'CANCELLED'
	}
}

/**
 * 网络请求管理器类
 */
class NetworkManager {
	constructor() {
		// 基础配置
		this.baseURL = ''
		this.defaultHeaders = {
			'Content-Type': 'application/json',
			'Accept': 'application/json'
		}
		this.defaultTimeout = 10000
		
		// 拦截器
		this.requestInterceptors = []
		this.responseInterceptors = []
		
		// 请求队列
		this.requestQueue = new Map()
		this.pendingRequests = new Map()
		
		// 网络状态
		this.networkStatus = NETWORK_STATUS.UNKNOWN
		this.isOnline = true
		
		// 统计信息
		this.stats = {
			totalRequests: 0,
			successfulRequests: 0,
			failedRequests: 0,
			cachedRequests: 0,
			retriedRequests: 0,
			cancelledRequests: 0,
			totalResponseTime: 0,
			averageResponseTime: 0,
			startTime: Date.now()
		}
		
		// 配置选项
		this.config = {
			maxConcurrentRequests: 10,
			maxRetries: 3,
			defaultCacheTTL: 5 * 60 * 1000,
			enableGlobalCache: true,
			enableGlobalRetry: true,
			enableRequestDeduplication: true,
			enableNetworkStatusMonitoring: true,
			enableStats: true,
			requestTimeout: 10000,
			offlineQueueSize: 100
		}
		
		// 离线队列
		this.offlineQueue = []
		
		this.init()
	}
	
	/**
	 * 初始化网络管理器
	 */
	init() {
		this.loadConfig()
		this.setupNetworkStatusMonitoring()
		this.setupDefaultInterceptors()
		
		logInfo('网络请求管理器已初始化', {
			baseURL: this.baseURL,
			maxConcurrentRequests: this.config.maxConcurrentRequests
		})
	}
	
	/**
	 * 加载配置
	 */
	loadConfig() {
		try {
			if (typeof uni !== 'undefined') {
				const saved = uni.getStorageSync('network_config')
				if (saved) {
					this.config = { ...this.config, ...saved }
				}
				
				const savedBaseURL = uni.getStorageSync('network_base_url')
				if (savedBaseURL) {
					this.baseURL = savedBaseURL
				}
			}
		} catch (error) {
			logError('加载网络配置失败', { error: error.message })
		}
	}
	
	/**
	 * 保存配置
	 */
	saveConfig() {
		try {
			if (typeof uni !== 'undefined') {
				uni.setStorageSync('network_config', this.config)
				uni.setStorageSync('network_base_url', this.baseURL)
			}
		} catch (error) {
			logError('保存网络配置失败', { error: error.message })
		}
	}
	
	/**
	 * 设置网络状态监控
	 */
	setupNetworkStatusMonitoring() {
		if (!this.config.enableNetworkStatusMonitoring) return
		
		try {
			if (typeof uni !== 'undefined') {
				// uni-app环境
				uni.onNetworkStatusChange((res) => {
					this.handleNetworkStatusChange(res.isConnected, res.networkType)
				})
				
				// 获取初始网络状态
				uni.getNetworkType({
					success: (res) => {
						this.handleNetworkStatusChange(res.networkType !== 'none', res.networkType)
					}
				})
			} else if (typeof window !== 'undefined') {
				// 浏览器环境
				window.addEventListener('online', () => {
					this.handleNetworkStatusChange(true, 'wifi')
				})
				
				window.addEventListener('offline', () => {
					this.handleNetworkStatusChange(false, 'none')
				})
				
				// 初始状态
				this.handleNetworkStatusChange(navigator.onLine, 'wifi')
			}
		} catch (error) {
			logError('设置网络状态监控失败', { error: error.message })
		}
	}
	
	/**
	 * 处理网络状态变化
	 * @param {boolean} isConnected - 是否连接
	 * @param {string} networkType - 网络类型
	 */
	handleNetworkStatusChange(isConnected, networkType) {
		const oldStatus = this.networkStatus
		const oldOnline = this.isOnline
		
		this.isOnline = isConnected
		this.networkStatus = isConnected ? NETWORK_STATUS.ONLINE : NETWORK_STATUS.OFFLINE
		
		logInfo('网络状态变化', {
			isConnected,
			networkType,
			oldStatus,
			newStatus: this.networkStatus
		})
		
		// 网络恢复时处理离线队列
		if (!oldOnline && isConnected) {
			this.processOfflineQueue()
		}
	}
	
	/**
	 * 设置默认拦截器
	 */
	setupDefaultInterceptors() {
		// 请求拦截器：添加认证头
		this.addRequestInterceptor((config) => {
			// 添加认证token
			const token = this.getAuthToken()
			if (token) {
				config.headers.Authorization = `Bearer ${token}`
			}
			
			// 添加设备信息
			config.headers['X-Device-ID'] = this.getDeviceId()
			config.headers['X-App-Version'] = this.getAppVersion()
			
			return config
		})
		
		// 响应拦截器：处理通用错误
		this.addResponseInterceptor(
			(response) => {
				// 成功响应处理
				return response
			},
			(error) => {
				// 错误响应处理
				if (error.response) {
					switch (error.response.status) {
						case 401:
							// 未授权，清除token
							this.clearAuthToken()
							break
						case 403:
							// 禁止访问
							logWarn('访问被禁止', { url: error.config.url })
							break
						case 429:
							// 请求过于频繁
							logWarn('请求过于频繁', { url: error.config.url })
							break
						case 500:
							// 服务器错误
							logError('服务器内部错误', { url: error.config.url })
							break
					}
				}
				
				return Promise.reject(error)
			}
		)
	}
	
	/**
	 * 发送请求
	 * @param {string|RequestConfig} urlOrConfig - URL或请求配置
	 * @param {Object} options - 选项
	 * @returns {Promise} 请求Promise
	 */
	request(urlOrConfig, options = {}) {
		let config
		
		if (typeof urlOrConfig === 'string') {
			config = new RequestConfig({ url: urlOrConfig, ...options })
		} else {
			config = urlOrConfig instanceof RequestConfig ? urlOrConfig : new RequestConfig(urlOrConfig)
		}
		
		// 应用基础URL
		if (this.baseURL && !config.url.startsWith('http')) {
			config.url = this.baseURL + config.url
		}
		
		// 合并默认头部
		config.headers = { ...this.defaultHeaders, ...config.headers }
		
		// 应用默认超时
		if (!config.timeout) {
			config.timeout = this.defaultTimeout
		}
		
		return this.executeRequest(config)
	}
	
	/**
	 * 执行请求
	 * @param {RequestConfig} config - 请求配置
	 * @returns {Promise} 请求Promise
	 */
	async executeRequest(config) {
		const requestId = this.generateRequestId()
		const startTime = Date.now()
		
		try {
			// 更新统计
			if (this.config.enableStats) {
				this.stats.totalRequests++
			}
			
			// 检查网络状态
			if (!this.isOnline && config.cacheStrategy !== CACHE_STRATEGIES.CACHE_ONLY) {
				return this.handleOfflineRequest(config)
			}
			
			// 检查并发限制
			if (this.pendingRequests.size >= this.config.maxConcurrentRequests) {
				await this.waitForSlot()
			}
			
			// 请求去重
			if (this.config.enableRequestDeduplication) {
				const duplicateRequest = this.findDuplicateRequest(config)
				if (duplicateRequest) {
					return duplicateRequest
				}
			}
			
			// 应用请求拦截器
			if (config.enableInterceptors) {
				config = await this.applyRequestInterceptors(config)
			}
			
			// 处理缓存策略
			const cacheResult = await this.handleCacheStrategy(config)
			if (cacheResult) {
				return cacheResult
			}
			
			// 执行网络请求
			const requestPromise = this.performNetworkRequest(config, requestId)
			this.pendingRequests.set(requestId, requestPromise)
			
			const response = await requestPromise
			
			// 应用响应拦截器
			if (config.enableInterceptors) {
				response = await this.applyResponseInterceptors(response)
			}
			
			// 缓存响应
			if (config.enableCache && this.shouldCacheResponse(config, response)) {
				this.cacheResponse(config, response)
			}
			
			// 更新统计
			if (this.config.enableStats) {
				this.stats.successfulRequests++
				this.updateResponseTimeStats(Date.now() - startTime)
			}
			
			return response
		} catch (error) {
			// 处理重试
			if (config.enableRetry && this.shouldRetry(error, config)) {
				return this.retryRequest(config, error)
			}
			
			// 更新统计
			if (this.config.enableStats) {
				this.stats.failedRequests++
			}
			
			throw error
		} finally {
			this.pendingRequests.delete(requestId)
		}
	}
	
	/**
	 * 执行网络请求
	 * @param {RequestConfig} config - 请求配置
	 * @param {string} requestId - 请求ID
	 * @returns {Promise} 请求Promise
	 */
	performNetworkRequest(config, requestId) {
		return new Promise((resolve, reject) => {
			const requestOptions = {
				url: config.url,
				method: config.method,
				data: config.data,
				header: config.headers,
				timeout: config.timeout,
				dataType: config.responseType === 'json' ? 'json' : 'text',
				responseType: config.responseType,
				success: (res) => {
					const response = new RequestResponse(
						res.data,
						res.statusCode,
						res.header,
						config,
						requestId
					)
					
					if (config.validateStatus(res.statusCode)) {
						resolve(response)
					} else {
						const error = new RequestError(
							`Request failed with status ${res.statusCode}`,
							'HTTP_ERROR',
							config,
							requestId,
							response
						)
						reject(error)
					}
				},
				fail: (err) => {
					let errorCode = 'NETWORK_ERROR'
					let errorMessage = err.errMsg || 'Network request failed'
					
					if (err.errMsg && err.errMsg.includes('timeout')) {
						errorCode = 'TIMEOUT'
						errorMessage = 'Request timeout'
					}
					
					const error = new RequestError(
						errorMessage,
						errorCode,
						config,
						requestId
					)
					
					reject(error)
				}
			}
			
			// 处理上传进度
			if (config.onUploadProgress) {
				requestOptions.uploadProgress = config.onUploadProgress
			}
			
			// 处理下载进度
			if (config.onDownloadProgress) {
				requestOptions.downloadProgress = config.onDownloadProgress
			}
			
			// 发送请求
			if (typeof uni !== 'undefined') {
				uni.request(requestOptions)
			} else {
				// 浏览器环境的fetch实现
				this.fetchRequest(requestOptions).then(resolve).catch(reject)
			}
		})
	}
	
	/**
	 * 浏览器fetch请求实现
	 * @param {Object} options - 请求选项
	 * @returns {Promise} 请求Promise
	 */
	async fetchRequest(options) {
		const fetchOptions = {
			method: options.method,
			headers: options.header,
			body: options.data ? JSON.stringify(options.data) : undefined
		}
		
		const controller = new AbortController()
		fetchOptions.signal = controller.signal
		
		// 设置超时
		const timeoutId = setTimeout(() => {
			controller.abort()
		}, options.timeout)
		
		try {
			const response = await fetch(options.url, fetchOptions)
			clearTimeout(timeoutId)
			
			let data
			if (options.dataType === 'json') {
				data = await response.json()
			} else {
				data = await response.text()
			}
			
			return {
				data,
				statusCode: response.status,
				header: Object.fromEntries(response.headers.entries())
			}
		} catch (error) {
			clearTimeout(timeoutId)
			
			if (error.name === 'AbortError') {
				throw { errMsg: 'request:fail timeout' }
			}
			
			throw { errMsg: error.message }
		}
	}
	
	/**
	 * 处理缓存策略
	 * @param {RequestConfig} config - 请求配置
	 * @returns {Promise|null} 缓存结果
	 */
	async handleCacheStrategy(config) {
		if (!config.enableCache || !this.config.enableGlobalCache) {
			return null
		}
		
		const cacheKey = config.generateCacheKey()
		const cachedResponse = getCache(cacheKey)
		
		switch (config.cacheStrategy) {
			case CACHE_STRATEGIES.CACHE_FIRST:
				if (cachedResponse) {
					cachedResponse.fromCache = true
					if (this.config.enableStats) {
						this.stats.cachedRequests++
					}
					return cachedResponse
				}
				break
			
			case CACHE_STRATEGIES.CACHE_ONLY:
				if (cachedResponse) {
					cachedResponse.fromCache = true
					if (this.config.enableStats) {
						this.stats.cachedRequests++
					}
					return cachedResponse
				} else {
					throw new RequestError('No cached response available', 'CACHE_MISS', config)
				}
			
			case CACHE_STRATEGIES.STALE_WHILE_REVALIDATE:
				if (cachedResponse) {
					// 返回缓存数据，同时在后台更新
					setTimeout(() => {
						this.performNetworkRequest(config, this.generateRequestId())
							.then(response => this.cacheResponse(config, response))
							.catch(() => {}) // 忽略后台更新错误
					}, 0)
					
					cachedResponse.fromCache = true
					if (this.config.enableStats) {
						this.stats.cachedRequests++
					}
					return cachedResponse
				}
				break
			
			case CACHE_STRATEGIES.NETWORK_FIRST:
			case CACHE_STRATEGIES.NETWORK_ONLY:
			default:
				// 继续网络请求
				break
		}
		
		return null
	}
	
	/**
	 * 缓存响应
	 * @param {RequestConfig} config - 请求配置
	 * @param {RequestResponse} response - 响应对象
	 */
	cacheResponse(config, response) {
		if (!this.shouldCacheResponse(config, response)) {
			return
		}
		
		const cacheKey = config.generateCacheKey()
		const cacheOptions = {
			ttl: config.cacheTTL,
			tags: ['network_cache', ...config.tags],
			persistent: false
		}
		
		setCache(cacheKey, response, cacheOptions)
	}
	
	/**
	 * 判断是否应该缓存响应
	 * @param {RequestConfig} config - 请求配置
	 * @param {RequestResponse} response - 响应对象
	 * @returns {boolean} 是否应该缓存
	 */
	shouldCacheResponse(config, response) {
		// 只缓存GET请求
		if (config.method !== REQUEST_METHODS.GET) {
			return false
		}
		
		// 只缓存成功响应
		if (!config.validateStatus(response.status)) {
			return false
		}
		
		// 检查缓存控制头
		const cacheControl = response.headers['cache-control'] || response.headers['Cache-Control']
		if (cacheControl && cacheControl.includes('no-cache')) {
			return false
		}
		
		return true
	}
	
	/**
	 * 重试请求
	 * @param {RequestConfig} config - 请求配置
	 * @param {Error} error - 错误对象
	 * @returns {Promise} 重试Promise
	 */
	async retryRequest(config, error) {
		if (!config.retries || config.retries <= 0) {
			throw error
		}
		
		const retryCount = (config.metadata.retryCount || 0) + 1
		if (retryCount > config.retries) {
			throw error
		}
		
		// 计算重试延迟
		const delay = this.calculateRetryDelay(config, retryCount)
		
		logInfo('重试请求', {
			url: config.url,
			retryCount,
			delay,
			error: error.message
		})
		
		// 等待延迟
		await this.sleep(delay)
		
		// 更新重试计数
		config.metadata.retryCount = retryCount
		
		// 更新统计
		if (this.config.enableStats) {
			this.stats.retriedRequests++
		}
		
		// 重新执行请求
		return this.executeRequest(config)
	}
	
	/**
	 * 计算重试延迟
	 * @param {RequestConfig} config - 请求配置
	 * @param {number} retryCount - 重试次数
	 * @returns {number} 延迟时间（毫秒）
	 */
	calculateRetryDelay(config, retryCount) {
		switch (config.retryStrategy) {
			case RETRY_STRATEGIES.LINEAR:
				return config.retryDelay * retryCount
			
			case RETRY_STRATEGIES.EXPONENTIAL:
				return config.retryDelay * Math.pow(2, retryCount - 1)
			
			case RETRY_STRATEGIES.FIXED:
				return config.retryDelay
			
			case RETRY_STRATEGIES.CUSTOM:
				if (typeof config.customRetryDelay === 'function') {
					return config.customRetryDelay(retryCount)
				}
				return config.retryDelay
			
			default:
				return config.retryDelay
		}
	}
	
	/**
	 * 判断是否应该重试
	 * @param {Error} error - 错误对象
	 * @param {RequestConfig} config - 请求配置
	 * @returns {boolean} 是否应该重试
	 */
	shouldRetry(error, config) {
		// 取消的请求不重试
		if (error.isCancelled) {
			return false
		}
		
		// 4xx错误通常不重试（除了408, 429）
		if (error.response && error.response.status >= 400 && error.response.status < 500) {
			return error.response.status === 408 || error.response.status === 429
		}
		
		// 网络错误和5xx错误可以重试
		return error.isNetworkError || error.isTimeout || 
			   (error.response && error.response.status >= 500)
	}
	
	/**
	 * 处理离线请求
	 * @param {RequestConfig} config - 请求配置
	 * @returns {Promise} 离线处理Promise
	 */
	handleOfflineRequest(config) {
		// 尝试从缓存获取
		if (config.enableCache) {
			const cacheKey = config.generateCacheKey()
			const cachedResponse = getCache(cacheKey)
			if (cachedResponse) {
				cachedResponse.fromCache = true
				return Promise.resolve(cachedResponse)
			}
		}
		
		// 添加到离线队列
		if (this.offlineQueue.length < this.config.offlineQueueSize) {
			this.offlineQueue.push(config)
			logInfo('请求已添加到离线队列', { url: config.url })
		}
		
		return Promise.reject(new RequestError('Network is offline', 'OFFLINE', config))
	}
	
	/**
	 * 处理离线队列
	 */
	async processOfflineQueue() {
		if (this.offlineQueue.length === 0) {
			return
		}
		
		logInfo('开始处理离线队列', { queueSize: this.offlineQueue.length })
		
		const queue = [...this.offlineQueue]
		this.offlineQueue = []
		
		for (const config of queue) {
			try {
				await this.executeRequest(config)
			} catch (error) {
				logWarn('离线队列请求失败', { url: config.url, error: error.message })
			}
		}
	}
	
	/**
	 * 查找重复请求
	 * @param {RequestConfig} config - 请求配置
	 * @returns {Promise|null} 重复请求Promise
	 */
	findDuplicateRequest(config) {
		const requestKey = config.generateCacheKey()
		
		for (const [id, promise] of this.pendingRequests) {
			if (promise.config && promise.config.generateCacheKey() === requestKey) {
				return promise
			}
		}
		
		return null
	}
	
	/**
	 * 等待请求槽位
	 * @returns {Promise} 等待Promise
	 */
	waitForSlot() {
		return new Promise((resolve) => {
			const checkSlot = () => {
				if (this.pendingRequests.size < this.config.maxConcurrentRequests) {
					resolve()
				} else {
					setTimeout(checkSlot, 100)
				}
			}
			checkSlot()
		})
	}
	
	/**
	 * 应用请求拦截器
	 * @param {RequestConfig} config - 请求配置
	 * @returns {Promise<RequestConfig>} 处理后的配置
	 */
	async applyRequestInterceptors(config) {
		let processedConfig = config
		
		for (const interceptor of this.requestInterceptors) {
			try {
				processedConfig = await interceptor(processedConfig)
			} catch (error) {
				logError('请求拦截器执行失败', { error: error.message })
				throw error
			}
		}
		
		return processedConfig
	}
	
	/**
	 * 应用响应拦截器
	 * @param {RequestResponse} response - 响应对象
	 * @returns {Promise<RequestResponse>} 处理后的响应
	 */
	async applyResponseInterceptors(response) {
		let processedResponse = response
		
		for (const interceptor of this.responseInterceptors) {
			try {
				if (interceptor.fulfilled) {
					processedResponse = await interceptor.fulfilled(processedResponse)
				}
			} catch (error) {
				if (interceptor.rejected) {
					processedResponse = await interceptor.rejected(error)
				} else {
					throw error
				}
			}
		}
		
		return processedResponse
	}
	
	/**
	 * 添加请求拦截器
	 * @param {Function} interceptor - 拦截器函数
	 * @returns {number} 拦截器ID
	 */
	addRequestInterceptor(interceptor) {
		this.requestInterceptors.push(interceptor)
		return this.requestInterceptors.length - 1
	}
	
	/**
	 * 添加响应拦截器
	 * @param {Function} fulfilled - 成功处理函数
	 * @param {Function} rejected - 失败处理函数
	 * @returns {number} 拦截器ID
	 */
	addResponseInterceptor(fulfilled, rejected) {
		const interceptor = { fulfilled, rejected }
		this.responseInterceptors.push(interceptor)
		return this.responseInterceptors.length - 1
	}
	
	/**
	 * 移除请求拦截器
	 * @param {number} id - 拦截器ID
	 */
	removeRequestInterceptor(id) {
		if (id >= 0 && id < this.requestInterceptors.length) {
			this.requestInterceptors.splice(id, 1)
		}
	}
	
	/**
	 * 移除响应拦截器
	 * @param {number} id - 拦截器ID
	 */
	removeResponseInterceptor(id) {
		if (id >= 0 && id < this.responseInterceptors.length) {
			this.responseInterceptors.splice(id, 1)
		}
	}
	
	/**
	 * GET请求
	 * @param {string} url - 请求URL
	 * @param {Object} options - 选项
	 * @returns {Promise} 请求Promise
	 */
	get(url, options = {}) {
		return this.request(url, { ...options, method: REQUEST_METHODS.GET })
	}
	
	/**
	 * POST请求
	 * @param {string} url - 请求URL
	 * @param {any} data - 请求数据
	 * @param {Object} options - 选项
	 * @returns {Promise} 请求Promise
	 */
	post(url, data, options = {}) {
		return this.request(url, { ...options, method: REQUEST_METHODS.POST, data })
	}
	
	/**
	 * PUT请求
	 * @param {string} url - 请求URL
	 * @param {any} data - 请求数据
	 * @param {Object} options - 选项
	 * @returns {Promise} 请求Promise
	 */
	put(url, data, options = {}) {
		return this.request(url, { ...options, method: REQUEST_METHODS.PUT, data })
	}
	
	/**
	 * DELETE请求
	 * @param {string} url - 请求URL
	 * @param {Object} options - 选项
	 * @returns {Promise} 请求Promise
	 */
	delete(url, options = {}) {
		return this.request(url, { ...options, method: REQUEST_METHODS.DELETE })
	}
	
	/**
	 * PATCH请求
	 * @param {string} url - 请求URL
	 * @param {any} data - 请求数据
	 * @param {Object} options - 选项
	 * @returns {Promise} 请求Promise
	 */
	patch(url, data, options = {}) {
		return this.request(url, { ...options, method: REQUEST_METHODS.PATCH, data })
	}
	
	/**
	 * 取消所有请求
	 */
	cancelAllRequests() {
		for (const [id, promise] of this.pendingRequests) {
			if (promise.cancel) {
				promise.cancel()
			}
		}
		
		this.pendingRequests.clear()
		
		if (this.config.enableStats) {
			this.stats.cancelledRequests += this.pendingRequests.size
		}
	}
	
	/**
	 * 设置基础URL
	 * @param {string} baseURL - 基础URL
	 */
	setBaseURL(baseURL) {
		this.baseURL = baseURL
		this.saveConfig()
	}
	
	/**
	 * 设置默认头部
	 * @param {Object} headers - 头部对象
	 */
	setDefaultHeaders(headers) {
		this.defaultHeaders = { ...this.defaultHeaders, ...headers }
	}
	
	/**
	 * 设置默认超时
	 * @param {number} timeout - 超时时间
	 */
	setDefaultTimeout(timeout) {
		this.defaultTimeout = timeout
	}
	
	/**
	 * 更新配置
	 * @param {Object} newConfig - 新配置
	 */
	updateConfig(newConfig) {
		this.config = { ...this.config, ...newConfig }
		this.saveConfig()
	}
	
	/**
	 * 获取统计信息
	 * @returns {Object} 统计信息
	 */
	getStats() {
		const successRate = this.stats.totalRequests > 0 
			? (this.stats.successfulRequests / this.stats.totalRequests * 100).toFixed(2)
			: 0
		
		return {
			...this.stats,
			successRate: `${successRate}%`,
			pendingRequests: this.pendingRequests.size,
			offlineQueueSize: this.offlineQueue.length,
			networkStatus: this.networkStatus,
			isOnline: this.isOnline,
			uptime: Date.now() - this.stats.startTime
		}
	}
	
	/**
	 * 清除缓存
	 * @param {string|Array} tags - 标签
	 */
	clearCache(tags) {
		if (tags) {
			deleteCacheByTags(tags)
		} else {
			deleteCacheByTags(['network_cache'])
		}
	}
	
	/**
	 * 重置统计
	 */
	resetStats() {
		this.stats = {
			totalRequests: 0,
			successfulRequests: 0,
			failedRequests: 0,
			cachedRequests: 0,
			retriedRequests: 0,
			cancelledRequests: 0,
			totalResponseTime: 0,
			averageResponseTime: 0,
			startTime: Date.now()
		}
	}
	
	/**
	 * 生成请求ID
	 * @returns {string} 请求ID
	 */
	generateRequestId() {
		return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
	}
	
	/**
	 * 更新响应时间统计
	 * @param {number} responseTime - 响应时间
	 */
	updateResponseTimeStats(responseTime) {
		this.stats.totalResponseTime += responseTime
		this.stats.averageResponseTime = this.stats.totalResponseTime / this.stats.successfulRequests
	}
	
	/**
	 * 获取认证token
	 * @returns {string|null} 认证token
	 */
	getAuthToken() {
		try {
			if (typeof uni !== 'undefined') {
				return uni.getStorageSync('auth_token')
			} else {
				return localStorage.getItem('auth_token')
			}
		} catch {
			return null
		}
	}
	
	/**
	 * 清除认证token
	 */
	clearAuthToken() {
		try {
			if (typeof uni !== 'undefined') {
				uni.removeStorageSync('auth_token')
			} else {
				localStorage.removeItem('auth_token')
			}
		} catch {
			// 忽略错误
		}
	}
	
	/**
	 * 获取设备ID
	 * @returns {string} 设备ID
	 */
	getDeviceId() {
		try {
			if (typeof uni !== 'undefined') {
				return uni.getStorageSync('device_id') || 'unknown'
			} else {
				return localStorage.getItem('device_id') || 'web_device'
			}
		} catch {
			return 'unknown'
		}
	}
	
	/**
	 * 获取应用版本
	 * @returns {string} 应用版本
	 */
	getAppVersion() {
		return '1.0.0' // 可以从配置文件或其他地方获取
	}
	
	/**
	 * 睡眠函数
	 * @param {number} ms - 毫秒数
	 * @returns {Promise} 睡眠Promise
	 */
	sleep(ms) {
		return new Promise(resolve => setTimeout(resolve, ms))
	}
	
	/**
	 * 销毁网络管理器
	 */
	destroy() {
		this.cancelAllRequests()
		this.saveConfig()
		
		logInfo('网络请求管理器已销毁')
	}
}

// 创建全局实例
const networkManager = new NetworkManager()

// 便捷方法
export const request = (urlOrConfig, options) => {
	return networkManager.request(urlOrConfig, options)
}

export const get = (url, options) => {
	return networkManager.get(url, options)
}

export const post = (url, data, options) => {
	return networkManager.post(url, data, options)
}

export const put = (url, data, options) => {
	return networkManager.put(url, data, options)
}

export const del = (url, options) => {
	return networkManager.delete(url, options)
}

export const patch = (url, data, options) => {
	return networkManager.patch(url, data, options)
}

export const setBaseURL = (baseURL) => {
	networkManager.setBaseURL(baseURL)
}

export const setDefaultHeaders = (headers) => {
	networkManager.setDefaultHeaders(headers)
}

export const setDefaultTimeout = (timeout) => {
	networkManager.setDefaultTimeout(timeout)
}

export const addRequestInterceptor = (interceptor) => {
	return networkManager.addRequestInterceptor(interceptor)
}

export const addResponseInterceptor = (fulfilled, rejected) => {
	return networkManager.addResponseInterceptor(fulfilled, rejected)
}

export const removeRequestInterceptor = (id) => {
	networkManager.removeRequestInterceptor(id)
}

export const removeResponseInterceptor = (id) => {
	networkManager.removeResponseInterceptor(id)
}

export const cancelAllRequests = () => {
	networkManager.cancelAllRequests()
}

export const getNetworkStats = () => {
	return networkManager.getStats()
}

export const clearNetworkCache = (tags) => {
	networkManager.clearCache(tags)
}

export const resetNetworkStats = () => {
	networkManager.resetStats()
}

export const updateNetworkConfig = (config) => {
	networkManager.updateConfig(config)
}

// 导出类和常量
export {
	RequestConfig,
	RequestResponse,
	RequestError
}

// 导出管理器实例
export default networkManager